<template>
    <el-row id="myRow1">
        <p id="myP1_left">
            <el-icon><Fold /></el-icon>
            <span style="color: #000;">客服</span>
            <span>/</span>
            <span>用户提现</span>
        </p>
        <p></p>
    </el-row>
    <el-row id="myRow2"></el-row>
    <el-form :inline="true" :model="myForm" id="myForm">
        <el-form-item>
            <el-select placeholder="请选择公司"></el-select>
        </el-form-item>
        <el-form-item>
            <el-input placeholder="请输入姓名" v-model="myForm.username"></el-input>
        </el-form-item>
        <el-form-item>
            <el-select placeholder="按申请时间"></el-select>
        </el-form-item>
        <el-form-item>
            <div class="demo-date-picker">
                <div class="block">
                <el-date-picker
                    v-model="myForm.value1"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间" 
                />
                </div>
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
    </el-form>
    <el-row id="myRow3">
        <p style="color: red;font-size: 20px;">提现合计:{{ totalAmount }}元</p>
        <el-button type="info" style="margin-bottom: 1em;" @click="handleRefresh"><el-icon><Refresh /></el-icon>刷新</el-button>
    </el-row>
    <el-table style="width: 100%;" border :data="tableData">
        <el-table-column label="姓名" prop="nickname" fixed="left"></el-table-column>
        <el-table-column label="手机号" prop="phone" width="200"></el-table-column>
        <el-table-column label="兑换比例（积分/现金）" prop="exchangeRate" width="200"></el-table-column>
        <el-table-column label="消费积分" prop="consumerPoints" width="200"></el-table-column>
        <el-table-column label="申请提现金额/元" prop="amount" width="200"></el-table-column>
        <el-table-column label="提现平台" prop="withdrawalPlatform" width="200"></el-table-column>
        <el-table-column label="来源" prop="source" width="200"></el-table-column>
        <el-table-column label="申请时间" prop="applyTime" width="200"></el-table-column>
        <el-table-column label="审核人" prop="shenheren" width="200"></el-table-column>
        <el-table-column label="审核时间" prop="shenheshijian" width="200"></el-table-column>
        <el-table-column label="打款状态" prop="status" width="200">
            <template #default="scoped">
                <el-tag :type="getStatusTagType(scoped.row.status)">
                    {{ getStatusText(scoped.row.status) }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column label="未通过原因" prop="weitongguoyuanyin" width="200"></el-table-column>
        <el-table-column label="备注" prop="note" width="200"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
            <template #default="scoped">
                <el-button @click="handleReview(scoped.row)" type="primary">
                     {{ getStatusText(scoped.row.status) }}
                </el-button>
            </template>
        </el-table-column>
    </el-table>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import {
    getDrawalListHistory
} from '@/components/api/UserCash'

let dialogReplace = ref(false);
let myForm = reactive({
    shoujihao:'',
    value1:'',
    username:''
})

let tableData = ref([])
let totalAmount = ref(0)

// 状态下拉选项
const statusOptions = [
    { code: 0, label: '待审核' },
    { code: 1, label: '通过' },
    { code: 2, label: '拒绝' },
    { code: 3, label: '打款中' },
    { code: 4, label: '失败' }
];

// 根据状态码获取对应的文本
const getStatusText = (statusCode) => {
    const option = statusOptions.find(opt => opt.code === statusCode);
    return option ? option.label : '未知';
};

// 获取状态标签类型
const getStatusTagType = (statusCode) => {
    switch(statusCode) {
        case 1: return 'success';
        case 2: return 'warning';
        case 3: return 'info';
        case 4: return 'danger';
        default: return 'primary';
    }
};

// 用户提现历史列表
let drawalList = ref([])
let getDrawalListFun = () => {
    const drawalListData = {
        pageIndex: parseInt(1),
        pageSize: parseInt(10),
    }
    getDrawalListHistory(drawalListData)
    .then(res => {
        if(res.code == 200){
            drawalList.value = res.dataset.list || []
            tableData.value = drawalList.value
            
            // 计算总金额
            totalAmount.value = drawalList.value.reduce((sum, item) => {
                return sum + (parseFloat(item.amount) || 0)
            }, 0).toFixed(2)
            
            console.log("历史列表数据已更新:", tableData.value)
        } else {
            console.log("接口返回错误", res.message)
            ElMessage.error('获取数据失败')
        }
    })
    .catch(err => {
        console.error("获取历史列表失败:", err)
        ElMessage.error('网络错误')
    })
}

// 刷新函数
const handleRefresh = () => {
    getDrawalListFun()
    ElMessage.success('数据已刷新')
}

// 审核操作
const handleReview = (row) => {
    // 这里可以添加审核逻辑
    ElMessage.info(`审核用户: ${row.nickname}`)
    dialogReplace.value = true
}

// 全局更新函数
window.updateWithdrawalHistory = () => {
    console.log("接收到更新信号，刷新历史列表...")
    getDrawalListFun()
}

// 页面可见性变化处理
const handleVisibilityChange = () => {
    if (!document.hidden) {
        console.log("页面变为可见，刷新数据...")
        getDrawalListFun()
    }
}

onMounted(() => {
    getDrawalListFun()
    
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', handleVisibilityChange)
    
    // 定时检查更新（每10秒检查一次）
    const intervalId = setInterval(() => {
        const lastUpdate = localStorage.getItem('withdrawalLastUpdate')
        if (lastUpdate && Date.now() - parseInt(lastUpdate) < 15000) { // 15秒内的更新
            getDrawalListFun()
            localStorage.removeItem('withdrawalLastUpdate')
        }
    }, 10000)
    window.withdrawalHistoryInterval = intervalId
})

onUnmounted(() => {
    // 清理事件监听
    document.removeEventListener('visibilitychange', handleVisibilityChange)
    
    // 清理定时器
    if (window.withdrawalHistoryInterval) {
        clearInterval(window.withdrawalHistoryInterval)
    }
    
    // 清理全局函数
    delete window.updateWithdrawalHistory
})

// 点击搜索执行搜索
const handleSearch = () => {
    const drawalListData = {
        pageIndex: parseInt(1),
        pageSize: parseInt(10),
        username: myForm.username
    }
    getDrawalListHistory(drawalListData)
    .then(res => {
        if(res.code === 200){
            drawalList.value = res.dataset.list || []
            tableData.value = drawalList.value
            
            // 重新计算总金额
            totalAmount.value = drawalList.value.reduce((sum, item) => {
                return sum + (parseFloat(item.amount) || 0)
            }, 0).toFixed(2)
        }
    })
}
</script>

<style scoped lang="less">
    #myRow1{
        border-bottom: 1px solid #ccc;
        padding: 0 1em;
        box-sizing: border-box;
        height: 3em;
        display: flex;
    }
    #myP1_left{
        height: 100%;
        display: flex;
        align-items: center;
        margin: 0;
        span{
            font-size: 14px;     
            margin-left: 0.7em;  
            color: #9AAABF; 
        }
    }
    #myRow2{
        height: 40px;
        align-items: center;
        padding: 0 1em;
        border-bottom: 1px solid #ccc;
    }
    #myForm{
        padding-left: 1.2em;
        padding-top: 1.3em;
        .el-form-item{
            width: 13%;
        }
        button{
            margin-left: 15em;
        }
    }
    #myRow3{
        align-items: center;
        justify-content: space-between;
        padding: 0 1em;
    }
    .myFormItem1{
        width: 45%;
    }
    .myFormItem2{
        width: 85%;
    }
</style>